package com.example.demo4

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.View.MeasureSpec
import com.example.demo4.model.Card

class CardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    
    private var card: Card? = null
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    
    init {
        paint.style = Paint.Style.FILL
        textPaint.style = Paint.Style.FILL
        textPaint.textAlign = Paint.Align.CENTER
        setBackgroundColor(Color.TRANSPARENT)
    }
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        
        val width: Int
        val height: Int
        
        if (widthMode == MeasureSpec.EXACTLY) {
            // 如果宽度是精确的（GridLayoutManager分配），使用它
            width = widthSize
            height = (width * 1.3f).toInt().coerceAtLeast(70)
        } else {
            // 否则计算合适的尺寸
            val screenWidth = resources.displayMetrics.widthPixels
            val padding = 24
            val availableWidth = screenWidth - padding
            val desiredWidth = (availableWidth / 4.5).toInt().coerceAtLeast(60).coerceAtMost(100)
            width = resolveSize(desiredWidth, widthMeasureSpec)
            height = (width * 1.3f).toInt().coerceAtLeast(70)
        }
        
        setMeasuredDimension(width, height)
        
        // 根据卡牌宽度动态调整文字大小
        textPaint.textSize = (width * 0.3f).coerceIn(20f, 36f)
    }
    
    fun setCard(card: Card) {
        this.card = card
        invalidate()
    }
    
    fun getCard(): Card? = card
    
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        val card = this.card ?: return
        
        val rect = RectF(1f, 1f, width.toFloat() - 1f, height.toFloat() - 1f)
        
        when {
            card.isMatched -> {
                // 已配对 - 浅绿色背景
                paint.color = Color.parseColor("#90EE90")
                paint.style = Paint.Style.FILL
                canvas.drawRoundRect(rect, 4f, 4f, paint)
                
                // 绘制边框
                paint.style = Paint.Style.STROKE
                paint.color = Color.parseColor("#228B22")
                paint.strokeWidth = 2f
                canvas.drawRoundRect(rect, 4f, 4f, paint)
                
                // 绘制对勾标记
                paint.color = Color.parseColor("#228B22")
                paint.strokeWidth = 4f
                paint.strokeCap = Paint.Cap.ROUND
                paint.strokeJoin = Paint.Join.ROUND
                val centerX = width / 2f
                val centerY = height / 2f
                val checkSize = width * 0.2f
                val path = Path()
                path.moveTo(centerX - checkSize * 0.4f, centerY)
                path.lineTo(centerX - checkSize * 0.1f, centerY + checkSize * 0.3f)
                path.lineTo(centerX + checkSize * 0.4f, centerY - checkSize * 0.2f)
                canvas.drawPath(path, paint)
                paint.style = Paint.Style.FILL
            }
            card.isChosen -> {
                // 已选中 - 显示卡牌内容，添加高亮边框
                paint.color = Color.WHITE
                paint.style = Paint.Style.FILL
                canvas.drawRoundRect(rect, 4f, 4f, paint)
                
                // 绘制选中高亮边框
                paint.style = Paint.Style.STROKE
                paint.color = Color.parseColor("#FF6B6B")
                paint.strokeWidth = 3f
                canvas.drawRoundRect(rect, 4f, 4f, paint)
                paint.style = Paint.Style.FILL
                
                // 绘制卡牌文字
                textPaint.color = when {
                    card.toString().contains("♥") || card.toString().contains("♦") -> Color.parseColor("#DC143C")
                    else -> Color.BLACK
                }
                
                val text = card.toString()
                val x = width / 2f
                val y = height / 2f - (textPaint.descent() + textPaint.ascent()) / 2
                canvas.drawText(text, x, y, textPaint)
            }
            else -> {
                // 未选中 - 显示背面（蓝色背景加X）
                paint.color = Color.parseColor("#4169E1")
                paint.style = Paint.Style.FILL
                canvas.drawRoundRect(rect, 4f, 4f, paint)
                
                // 绘制边框
                paint.style = Paint.Style.STROKE
                paint.color = Color.parseColor("#1E3A8A")
                paint.strokeWidth = 2f
                canvas.drawRoundRect(rect, 4f, 4f, paint)
                
                // 绘制X标记
                paint.color = Color.WHITE
                paint.strokeWidth = 4f
                paint.strokeCap = Paint.Cap.ROUND
                val margin = (width * 0.2f).coerceAtLeast(8f)
                canvas.drawLine(margin, margin, width - margin, height - margin, paint)
                canvas.drawLine(width - margin, margin, margin, height - margin, paint)
                paint.style = Paint.Style.FILL
            }
        }
    }
}

